#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define LONGFRASE 1000
#define LONGPALABRA 20
#define CANTPALABRA 500

int ExtraerPalabras (char[], char[][LONGPALABRA]);
void OrdenarAlfa (char Palabras[][LONGPALABRA], int);
void Cambiar (char[],char[]);

int main (void)
{
	char Frase[LONGFRASE+1], Palabras[CANTPALABRA][LONGPALABRA];
	int lonfrase, tot_pal;
	
	printf ("Escriba una frase de hasta 1000 caracteres:\n\n\t");
	gets (Frase);
	lonfrase= strlen(Frase);
	
	tot_pal= ExtraerPalabras (Frase, Palabras);
	
	OrdenarAlfa (Palabras, tot_pal);
	
	return 0;
}

int ExtraerPalabras (char origen[], char destino[][LONGPALABRA])
{
	int i, j, palabra;
	
	i = 0;
	while (i<LONGFRASE && !isalpha(origen[i])) i++; /* Saltarse las no-letras iniciales.*/
	
	palabra = 0;
	while (i<LONGFRASE){
		j = 0;
		while (i<LONGFRASE && isalpha(origen[i])) destino[palabra][j++] = origen[i++];
		destino[palabra++][j] = '\0';
		
		if (palabra == CANTPALABRA)
			break;
		
		while (i<LONGFRASE && !isalpha(origen[i])) i++;
	}
	
	return palabra;
}

void OrdenarAlfa (char Palabras[][LONGPALABRA], int tot_pal)
{
	int Tam_completo, Tam_restante, i, j;
	
	Tam_completo= tot_pal-1;
	for (i=0; i<Tam_completo; i++){
		Tam_restante= tot_pal+1-i;
		for (j=0; j<Tam_restante; j++)
			if (strcmp(Palabras[j], Palabras[j+1])){
				Cambiar (Palabras[j], Palabras[j+1]);
			}
	}
}

void Cambiar (char A[],char B[])
{
	char Aux[1][LONGPALABRA];
		
	strcpy(Aux[0], A[0]);
	strcpy(A[0], B[0]);
	strcpy(B[0], Aux[0]);
}
